package com.shuqi.application;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.Looper;

import com.shuqi.common.MyTask;
import com.shuqi.common.Urls;
import com.shuqi.common.utils.Log4an;
import com.shuqi.model.net.CustomerHttpClient;
import com.shuqi.model.net.HttpFactory;
import com.shuqi.sdk.ad.ADView;

/**
 * 用于捕获错误日志，RELEASE设置为true之后，客户端不会崩溃
 */
public class ApplicationCrashHandler implements UncaughtExceptionHandler {

    public static final String TAG = "ApplicationCrashHandler";

    private static ApplicationCrashHandler crashHandler = new ApplicationCrashHandler();
    /**当前界面上显示的activity*/
    private static Activity curActivity;

    // 设为false就不会捕获全局异常
    public static final boolean RELEASE = true;

    private ApplicationCrashHandler() {}

    public static ApplicationCrashHandler getCrashHandlerInstances() {
        return crashHandler;
    }
    /** 当前页面被显示/创建/置空 */
    public static void showed(Activity activity){
        curActivity = activity;
    }
    /**移除当前页面 */
    public static void clear(){
        curActivity = null;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        Log4an.e(TAG, "Exception CurrentActivity: "+(curActivity==null?"null":curActivity.getLocalClassName()));
        String errorInfo = getErrorInfo(ex);
        ADView.recordAdCrashLog(ShuqiApplication.getContext(), errorInfo);
        // 错误信息上传服务器
        sendErrorMessage(errorInfo);
        //错误日志记录到文件
//        FileLog.getInstance().addLog(errorInfo);
        
    }

    private String getErrorInfo(Throwable throwable) {
        Writer writer = new StringWriter();
        PrintWriter pw = new PrintWriter(writer);
        throwable.printStackTrace(pw);
        String error = "";
        try {
            pw.close();
            writer.close();
        } catch (IOException e) {
        } finally {
            error = writer.toString();
        }
        return error;
    }

    // private boolean isTopActivity() {
    // ActivityManager am = (ActivityManager) ShuqiApplication.getContext()
    // .getSystemService(Context.ACTIVITY_SERVICE);
    // List<RunningTaskInfo> tasksInfo = am.getRunningTasks(1);
    // if (tasksInfo.size() > 0) {
    // if (ShuqiApplication.packageName
    // .equals(tasksInfo.get(0).topActivity.getPackageName())) {
    // return true;
    // }
    // }
    // return false;
    // }

    public void sendErrorMessage(final String errorInfo) {
        MyTask.runInBackground(new Runnable() {
            public void run() {
                Looper.prepare();
                try {
                    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
                    BasicNameValuePair p = new BasicNameValuePair("error_info", errorInfo);
                    params.add(p);
                    String url = Urls.getBUGSubmit(curActivity==null?"shuqi":curActivity.getClass().getSimpleName());
                    HttpRequestBase httpRequest =
                            HttpFactory.getHttpPostFromUrlStr(url,ShuqiApplication.getContext());
                    ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

                    HttpClient httpClient = CustomerHttpClient.getHttpClient();
                    HttpResponse httpResponse = httpClient.execute(httpRequest);
                    int code = httpResponse.getStatusLine().getStatusCode();
                    Log4an.e(TAG, "code=" + code+",errorInfo="+errorInfo);
                    reboot();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Looper.loop();
            }
        }, true);
    }
    /** 重启软件 */
    private void reboot() {
        if(curActivity!=null){
            curActivity.finish();
        }
        android.os.Process.killProcess(android.os.Process.myPid());
    }
}
